<?php
/**
 * JLD WX图片处理
 */
class WxpicModel {
    
    /**
     * 写入一条数据
     * 
     * @param int    $from_user
     * @param string $pic_url
     * @param int    $create_time
     */
    static public function create($from_user, $pic_url, $create_time) {
        $filepath = self::_showSavePath();
        
        register_shutdown_function(function() use ($filepath, $pic_url) {
            fastcgi_finish_request();
            $fp = fopen($filepath, 'w+');
            
            $ch = curl_init();
            curl_setopt_array($ch, array(
                CURLOPT_FILE => $fp,
                CURLOPT_URL => $pic_url,
            ));
            $result = curl_exec($ch);
            curl_close($ch);
            fclose($fp);
        });

        
        return $result;
    }
    
    /**
     * 获取当前保存的文件路径
     * 
     * @return string
     */
    public static function _showSavePath() {
        // 确认存储目录
        $time = time();
        $config_weixin = new \Yaf_Config_Ini(APP_PATH . 'conf/weixin.ini');
        $dir = $config_weixin->data->path;
        $dir .= date('Ymd/', $time);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        
        // 确定文件名
        $path_base = $dir . date('His');
        $ext_name = '.jpg';
        $path = $path_base . $ext_name;
        for ($i = 0; $i < 100; ++$i) {
            if (!is_file($path)) {
                break;
            }
            $path = $path_base . uniqid('_') . $ext_name;
        }
        
        return $path;
    }
}